# Copyright 2010 The Go Example Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

#
# Go语言项目构建Rakefile 
# 

#处理扩展名
def ext(fn, newext)
  fn.sub(/\.[^.]+$/, newext)
end

#与平台相关常量
O=8
G_AS="#{O}a"
G_CC="#{O}c"
G_GC="#{O}g"
G_LD="#{O}l"
G_GPK="gopack"
G_FMT="gofmt"

desc "默认任务(compile)。"
task :default => [:compile]

#项目名称
TARG="gojson"
SRCDIR="."
BINDIR="."
OBJDIR="."
OUTDIR="."

#源代码
#FILES = FileList['reader.go']
FILES = FileList['writer.go','reader.go']



#不处理的文件
#SRCFILES.exclude("test")
SRCFILES=FILES.collect {|fn| "#{SRCDIR}/#{fn}" }

#目标文件
OBJFILES = FILES.collect { |fn|
	filename=ext(fn,".8") 

	"#{OBJDIR}/#{filename}"
}

desc "编译项目源代码，并生成目标文件"
task :compile do
	puts "开始编译项目源代码..."

	#sh "#{G_GC} -o #{OBJFILES} #{SRCFILES}"

	FILES.each do |fn|
		srcfile="#{SRCDIR}/#{fn}"
		filename=ext(fn,".8")
		objfile="#{OBJDIR}/#{filename}"
		sh "#{G_GC} -o #{objfile} #{srcfile}"

	end 
end 

desc "链接目标文件，并生成可执行文件"
file "link" => :compile do |t|
	puts "开始链接目标文件..."
	#sh "#{G_LD} -o #{TARG}.exe #{OBJFILES}"

	
	FILES.each do |fn|
		filename=ext(fn,".8")
		objfile="#{OBJDIR}/#{filename}"
		fileexe=ext(fn,".exe")
		outfile="#{OUTDIR}/#{fileexe}"
		sh "#{G_LD} -o #{outfile} #{objfile}"
	end 
end

desc "运行生成的"
task :run => ["link"] do
  sh "#{TARG}.exe"
end

#"生成包文件"
file "#{TARG}.a" => :compile do
	puts "开始生成包文件..."
	sh "#{G_GPK} crg #{TARG}.a #{TARG}.8"
end 

desc "生成包文件"
task :pkg => ["#{TARG}.a"] do
	
end

desc "构建项目..."
task :build =>["link"] do
	puts "构建项目结束"
end 

desc "格式化源代码"
file "fmt"  do |t|
	puts "开始格式文件..."
	
	FILES.each do |fn|
		filename=ext(fn,".8")
		sh "#{G_FMT} -w #{fn} "
	end 
end

desc "删除生成的临时文件"
task :clean do
  rm_f FileList['*.8']
  Dir['*~'].each { |fn| rm_f fn }
end

desc "删除所有生成的文件"
task :clobber => [:clean] do
  rm_f FileList['*.a','*.exe']
end